//
//  BN_PingLunViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-3-31.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_PingLunViewController.h"
#import "BN_NoticeHelper.h"

@interface BN_PingLunViewController () {
    BN_DynamicHelper *dynamicHelper_;
    BN_NoticeHelper *noticeHelper_;
    
    int KEYBORAD_HEIGHT;
    float inputBoxViewHeight;
}

// add by jason yan 2014-05-22
/**
 *  释放资源
 */
- (void)releaseResources;

@end

@implementation BN_PingLunViewController

#pragma mark - Extend method

// 释放资源
- (void)releaseResources{
    
    [dynamicHelper_ cancelPostDynamicInfo];
    [dynamicHelper_ cancelQueryDetailInfo];
    [dynamicHelper_ cancelQueryListForClass];
    [dynamicHelper_ cancelQueryListForParent];
    dynamicHelper_ = nil;
    [noticeHelper_ cancelQueryNoticeDetail];
    [noticeHelper_ cancelQueryNoticeList];
    noticeHelper_ = nil;
    
    self.pinglunTableView.dataSource = nil;
    self.pinglunTableView.delegate = nil;
    self.pinglunTableView = nil;
    
    self.inputBoxView.inputBox.delegate = nil;
    [_inputBoxView.inputBox resignFirstResponder];
    self.inputBoxView = nil;
    
    // add by jason yan 2014-05-22
    [[NSNotificationCenter defaultCenter]removeObserver:self name:KPOPKEYBOARDHEIGHT object:nil];
    // KREFRESH_NOTICELIST
    [[NSNotificationCenter defaultCenter]removeObserver:self name:KREFRESH_NOTICELIST object:nil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"评论";
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    // 隐藏tabbar
    self.tabBarController.tabBar.hidden = YES;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"houtui"] style:UIBarButtonItemStylePlain target:self action:@selector(backMainVCAction)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    // 注册改变inputboxView frame 的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(inputBoxHeight:) name:KPOPKEYBOARDHEIGHT object:nil];
    
    // 列表适配IOS7
    self.pinglunTableView = [[UITableView alloc]init];
    if (MAIN_VERSION >= 7) {
        self.pinglunTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
        self.pinglunTableView.contentInset = UIEdgeInsetsMake(64, 0, 45, 0);
        self.pinglunTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 45, 0);
    }else {
        self.pinglunTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-HEIGHT_NAV_BAR-45);
    }

    if ([self.pinglunTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.pinglunTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    // 清楚多余边框
    [self setExtraCellLineHidden:self.pinglunTableView];
    self.pinglunTableView.delegate = self;
    self.pinglunTableView.dataSource = self;
    [self.view addSubview:self.pinglunTableView];
    
    //输入框UIView
    self.inputBoxView = [[[NSBundle mainBundle]loadNibNamed:@"BN_PingLunInput" owner:nil options:nil]objectAtIndex:0];
    self.inputBoxView.inputBox.delegate = self;
    self.inputBoxView.inputBox.scrollEnabled = NO;
    self.inputBoxView.layer.shadowOffset = CGSizeMake(1, 0);
    self.inputBoxView.layer.shadowColor = [[UIColor grayColor] CGColor];
    self.inputBoxView.layer.shadowOpacity = 0.5;
    self.inputBoxView.layer.shadowRadius = 1;
    
    if (MAIN_VERSION >= 7) {
        self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-45, SCREEN_WIDTH, 45);
        inputBoxViewHeight = self.inputBoxView.frame.size.height;
    }else {
        self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-45-HEIGHT_NAV_BAR, SCREEN_WIDTH, 45);
        inputBoxViewHeight = self.inputBoxView.frame.size.height;

    }
    self.inputBoxView.inputBox.placeholder = @"说点什么吧...";
    [self.inputBoxView.sendBtn addTarget:self action:@selector(sendMessageAction) forControlEvents:UIControlEventTouchUpInside];
    // YES 为键盘弹出
    BOOL type = [userDefaults boolForKey:@"USERDEFAULTS_PINGLUN_TYPE"];
    if (type) {
        [self.inputBoxView.inputBox becomeFirstResponder];
    }
    [self.view addSubview:self.inputBoxView];
    
    
    // 此判断是哪个页面push过来的
    self.dynamicOrNotice = [userDefaults integerForKey:USERDEFAULTS_DYNAMICORNOTICE];
    switch (self.dynamicOrNotice) {
        case 0:
            // 初始化动态Helper类
            if (!dynamicHelper_) {
                dynamicHelper_ = [[BN_DynamicHelper alloc]init];
            }
            [self netRequest];
            break;
        case 1:
            if (!noticeHelper_) {
                noticeHelper_ = [[BN_NoticeHelper alloc]init];
            }
            [self netRequest];
            break;
        default:
            break;
    }
    
    // 风火轮
    [self viewLoadHintView];
}

// 网络请求
// 动态
- (void)netRequest {
    
    // Test USERDEFAULTS_DYNAMICORNOTICE
    NSInteger testDynOrNot = [[NSUserDefaults standardUserDefaults] integerForKey:USERDEFAULTS_DYNAMICORNOTICE];
    NSLog(@"动态或通知：%ld",(long)testDynOrNot);
    __weak typeof(self) weakSelf = self;
    if (self.dynamicOrNotice == 0) {
        if ([dynamicHelper_ respondsToSelector:@selector(queryDetailWithPostId:completeHandler:)]) {
            [dynamicHelper_ queryDetailWithPostId:self.postId completeHandler:^(id result, NSString *errMsg) {
                // update by jason yan 2014-05-30
                if (errMsg) {
                    [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
                    [weakSelf cancelHintView];
                }
                if (result) {
                    [weakSelf receiveData:result];
                    [weakSelf cancelHintView];
                }
            }];
        }
    }
    if (self.dynamicOrNotice == 1) {
        [noticeHelper_ queryNoticeDetailWithId:self.postId completeHandler:^(id result, NSString *errMsg) {
            // update by jason yan 2014-05-30
            if (errMsg) {
                [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
                [weakSelf cancelHintView];
            }
            if(result){
                [weakSelf cancelHintView];
                [weakSelf receiveNoticeData:result];
            }
        }];
    }
}

// 处理网络数据，reloaddata tableView
// 动态
- (void)receiveData:(NSMutableDictionary *)dict {
    NSMutableArray *infoArr = dict[@"repls"];
    self.postIdArr = infoArr;
    [self.pinglunTableView reloadData];
}

// 通知
- (void)receiveNoticeData:(NSMutableArray *)arr {
    NSDictionary *receiveDict = arr[0];
    NSMutableArray *infoArr = receiveDict[@"repls"];
    self.postIdArr = infoArr;
    [self.pinglunTableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.postIdArr.count;
}

- (void)setExtraCellLineHidden:(UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    [tableView setTableFooterView:view];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"BN_PinglunCell";
    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_PinglunCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
        nibsRegistered = YES;
    }
    BN_PinglunCell *cell = (BN_PinglunCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    
    // 用户头像
    // 是否动态或通知
    NSString * postHeadUrlStr = nil;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger isDynamicOrNotice = [userDefaults integerForKey:USERDEFAULTS_DYNAMICORNOTICE];
    switch (isDynamicOrNotice) {
        case 0:
            postHeadUrlStr = self.postIdArr[indexPath.row][@"postHeadUrl"];
            break;
        case 1:
            postHeadUrlStr = self.postIdArr[indexPath.row][@"notiHeadUrl"];
            break;
        default:
            break;
    }
    
    if (![postHeadUrlStr isEqual:[NSNull null]]) {
        postHeadUrlStr = [THUMBNAIL_BASEURL stringByAppendingString:postHeadUrlStr];
        NSURL *postHeadUrl = [NSURL URLWithString:postHeadUrlStr];
        [cell.userPhoto setImageWithURL:postHeadUrl placeholderImage:[UIImage imageNamed:@"userPhoto"]];
        cell.userPhoto.layer.masksToBounds = YES;
        cell.userPhoto.layer.cornerRadius = 18;
    }else {
        cell.userPhoto.image = [UIImage imageNamed:@"userPhoto"];
    }
    
    
    // 用户名
    cell.userName.text = self.postIdArr[indexPath.row][@"replUserName"];
    
    // 内容
    cell.userContent.text = self.postIdArr[indexPath.row][@"replCont"];
    
    // 时间
    NSString *dateStr = self.postIdArr[indexPath.row][@"replDate"];
    NSRange rang = NSMakeRange(0, 19);
    NSString *strRang = [dateStr substringWithRange:rang];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateTime = [formatter dateFromString:strRang];
    cell.createTime.text = [IMB_TimeFormatModel timeFormat:dateTime];
    
    [cell changeRowHeight];
    [cell.userContent sizeToFit];

    return cell;
}

// 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BN_PinglunCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (MAIN_VERSION >= 7) {
        self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-inputBoxViewHeight, SCREEN_WIDTH, inputBoxViewHeight);
    }else {
        self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-inputBoxViewHeight-HEIGHT_NAV_BAR, SCREEN_WIDTH, inputBoxViewHeight);
    }
    [self.inputBoxView.inputBox resignFirstResponder];
}

#pragma mark 
#pragma mark 键盘弹起

- (void)inputBoxHeight:(NSNotification *)notification {
    [UIView animateWithDuration:0.3 animations:^{
        KEYBORAD_HEIGHT = [notification.object intValue];
        
        self.inputBoxView.hidden = NO;
        if (MAIN_VERSION >= 7) {
            self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-inputBoxViewHeight-KEYBORAD_HEIGHT, SCREEN_WIDTH, inputBoxViewHeight);
        }else {
            self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-inputBoxViewHeight-HEIGHT_NAV_BAR-KEYBORAD_HEIGHT, SCREEN_WIDTH, inputBoxViewHeight);
        }
    } completion:^(BOOL finished) {
        
        }];
}

#pragma mark
#pragma mark 发布信息按钮事件

- (void)backMainVCAction {
    
    [self releaseResources];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sendMessageAction {
    
    // 判断是发布班级动态 或 家长动态
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSInteger isClassParent = [userDefault integerForKey:USERDEFAULTS_CLASSPARENT];
    NSString *replConent = self.inputBoxView.inputBox.text;
    if (![self.inputBoxView.inputBox.text isEqualToString:@"说点什么吧..."] && self.inputBoxView.inputBox.text.length > 0) {
        switch (self.dynamicOrNotice) {
            case 0:
            {
                [dynamicHelper_ postReplyWithPostId:self.postId replCont:replConent compelteHandler:^(id result, NSString *errMsg) {
                    if (errMsg) {
                        [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
                    }else {
                        NSString *successStr = [NSString stringWithFormat:@"%@",result];
                        [LZCHINT title:successStr type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
                        
                        // 回复成功后
                        // 刷新评论列表 || 刷新动态首页
                        [self netRequest];
                        
                        // 刷新对应列表
                        switch (isClassParent) {
                            case 0:
                                [[NSNotificationCenter defaultCenter]postNotificationName:KCLASSAUTOREFRESH object:nil];
                                
                                break;
                            case 1:
                                [[NSNotificationCenter defaultCenter]postNotificationName:KPARENTAUTOREFRESH object:nil];
                                
                                break;
                            default:
                                break;
                        }
                        
                        // 判断输入View回到原位置
                        [self.inputBoxView.inputBox resignFirstResponder];
                        self.inputBoxView.inputBox.text = @"";
                        if (MAIN_VERSION >= 7) {
                            self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-45, SCREEN_WIDTH, 45);
                            inputBoxViewHeight = self.inputBoxView.frame.size.height;
                            self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, 35);
                            inputBoxViewHeight = self.inputBoxView.frame.size.height;
                            
                        }else {
                            self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-45-HEIGHT_NAV_BAR, SCREEN_WIDTH, 45);
                            self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, 35);
                            inputBoxViewHeight = self.inputBoxView.frame.size.height;
                        }
                    }
                }];
            }
                break;
            case 1:
            {
                [noticeHelper_ replyNoticeWithId:self.postId replyContent:replConent completeHandler:^(id result, NSString *errMsg) {
                    if (errMsg) {
                        [self netRequest];
                        
                        [self.inputBoxView.inputBox resignFirstResponder];
                        self.inputBoxView.inputBox.text = @"";
                        [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
                        
                        if (MAIN_VERSION >= 7) {
                            self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-45, SCREEN_WIDTH, 45);
                            inputBoxViewHeight = self.inputBoxView.frame.size.height;
                            self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, 35);
                            inputBoxViewHeight = self.inputBoxView.frame.size.height;                }else {
                                self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-45-HEIGHT_NAV_BAR, SCREEN_WIDTH, 45);
                                self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, 35);
                                inputBoxViewHeight = self.inputBoxView.frame.size.height;
                            }
                        
                        // 刷新通知列表
                        [[NSNotificationCenter defaultCenter]postNotificationName:KREFRESH_NOTICELIST object:nil];
                    }else{
                        NSLog(@"回复通知结果:%@",result);
                    }
                }];
            }
                break;
            default:
                break;
        }
    }else {
        [LZCHINT title:@"请您输入评论内容" type:LZCInfo duration:2 places:HINT_PLACES callBack:NULL];
    }
}

#pragma mark
#pragma mark TextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    
    UIFont * tfont = [UIFont systemFontOfSize:14];
    self.inputBoxView.inputBox.font = tfont;
    CGSize size =CGSizeMake(240,10000);
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
    
    switch (MAIN_VERSION) {
        case 7:
        {
            CGSize actualsize =[self.inputBoxView.inputBox.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:tdic context:nil].size;
            self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, (actualsize.height-16.7019997)+35);
            self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-45-KEYBORAD_HEIGHT-(actualsize.height-16.7019997), SCREEN_WIDTH, 45+(actualsize.height-16.7019997));
            inputBoxViewHeight = self.inputBoxView.frame.size.height;
        }
            break;
        case 6:
        {
            CGSize iOS6size = [self.inputBoxView.inputBox.text  sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
            
            if (iOS6size.height != 0) {
                self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, (iOS6size.height-18)+35);
                self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-inputBoxViewHeight-HEIGHT_NAV_BAR-KEYBORAD_HEIGHT, SCREEN_WIDTH, 45+(iOS6size.height-18));
            }else {
                self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, 35);

                self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-inputBoxViewHeight-HEIGHT_NAV_BAR-KEYBORAD_HEIGHT, SCREEN_WIDTH, 45);
            }
            
            inputBoxViewHeight = self.inputBoxView.frame.size.height;
        }
            break;
        default:
            break;
    }
}

- (void)dealloc
{
    [self releaseResources];
    NSLog(@"BN_PingLunViewController dealloc ....");
}

@end
